package main

import (
	"../client/library/common"
	"../client/library/ecdhSev"
	"../client/library/protocol"
	"../client/orm"
	"bytes"
	"flag"
	"github.com/gogf/gf/g"
	"github.com/gogf/gf/g/crypto/gaes"
	"github.com/gogf/gf/g/net/ghttp"
	"github.com/gogf/gf/g/os/glog"
	"github.com/gogf/gf/g/os/gtime"
	"github.com/gogf/gf/g/util/gconv"
	"github.com/gogo/protobuf/proto"
	"os"
	"runtime"
	"time"
)

func init() {
	defer func() {
		//必须要先声明defer，否则不能捕获到panic异常
		if err := recover(); err != nil {
			glog.Error("整个进程执行出现异常！err==>", err)
		}
	}()
	runtime.GOMAXPROCS(runtime.NumCPU())
	runPath := common.GetCurrentDirectory()
	Code := "default"
	c := g.Config()
	s := g.Server()
	s.EnablePprof()
	_ = c.SetPath(runPath + "/configs")
	companyCode := flag.String("code", Code, "")
	flag.Parse()
	s.SetLogPath(runPath + "/logs/" + *companyCode)
	s.SetLogStdout(true)
	glog.SetPath(runPath + "/logs/" + *companyCode)
	// 配置对象及视图对象配置
	_ = c.AddPath(runPath + "/configs")
	companyConfig := *companyCode + ".toml"
	c.SetFileName(companyConfig)
	orm.Db = g.DB("ecms")
}

func main() {
	ChangeCompany(1)
}

func ChangeCompany(checkNum int)  {
	id := "1"
	Client1 := ecdhSev.CreateECCKey("client")
	bytess:=bytes.NewBuffer(Client1.PubKey)
	bytess.Write(gconv.Bytes(id))
	urls := "http://127.0.0.1:8299/servicecheck/ecdh"
	//urls := "http://wujie.ec.wujieshuju.com/livecode/servicecheck/ecckey"
	res := HttpPost(urls,bytess.Bytes())
	if string(res) == "Internal Server Error" {
		if checkNum == 5 {
			glog.Error("网络请求出错:Internal Server Error")
			os.Exit(1)
		}else {
			checkNum++
			time.Sleep(10*time.Second)
			glog.Info("网络请求出错:Internal Server Error重试",checkNum)
			ChangeCompany(checkNum)
		}
	}
	if len(res) < 57 {
		if checkNum == 5 {
			glog.Error("网络请求出错:返回结果错误")
			os.Exit(1)
		}else {
			checkNum++
			time.Sleep(10*time.Second)
			glog.Info("网络请求出错:返回结果错误重试",checkNum)
			ChangeCompany(checkNum)
		}
	}
	spubkey:=bytes.NewBuffer(res[0:57])
	data:=res[57:]
	SharedSecret := Client1.ComputerECCKeyMD5(spubkey.Bytes())
	if SharedSecret == nil {
		if checkNum == 5 {
			glog.Error("网络请求出错502:返回结果错误")
			os.Exit(1)
		}else {
			checkNum++
			time.Sleep(10*time.Second)
			glog.Info("网络请求出错502:返回结果错误重试",checkNum)
			ChangeCompany(checkNum)
		}
	}
	d, err := gaes.Decrypt(data, SharedSecret)
	if err == nil {
		res := &protocol.Company{}
		err := proto.Unmarshal(d, res)
		if err != nil {
			if checkNum == 5 {
				glog.Error("校验结果出错")
				os.Exit(1)
			}else {
				checkNum++
				time.Sleep(10*time.Second)
				glog.Info("校验结果出错重试",checkNum)
				ChangeCompany(checkNum)
			}
		}
		if gconv.Int(res.Status) == 0{
			if checkNum == 5 {
				glog.Error("校验出错")
				os.Exit(1)
			}else {
				checkNum++
				time.Sleep(10*time.Second)
				glog.Info("校验出错重试",checkNum)
				ChangeCompany(checkNum)
			}
		}
		if gtime.NewFromStr(res.InvalidTime).Second() < gtime.Now().Second() {
			glog.Error("client用户已过期")
			os.Exit(1)
		}
		ass,_ := orm.GetUserCount()
		if gconv.Int32(ass) > res.Num {
			glog.Error("用户数大于最大值")
			os.Exit(1)
		}
	}else {
		if checkNum == 5 {
			glog.Error("网络请求出错")
			os.Exit(1)
		}else {
			checkNum++
			time.Sleep(10*time.Second)
			glog.Info("网络请求出错重试",checkNum)
			ChangeCompany(checkNum)
		}
	}
}

func HttpPost(url string,data []byte) []byte{
	//Console.WriteLine(shortUrl + Url_GCI);
	//{Accept: */*Content-Type: application/octet-streamUser-Agent: MicroMessenger ClientHost: hkshort.weixin.qq.comContent-Length: 275Expect: 100-continueConnection: Keep-Alive}
	http:=ghttp.NewClient()
	http.SetHeader("Accept","*/*")
	http.SetHeader("User-Agent","MicroMessenger Client")
	http.SetHeader("Content-Type","application/octet-stream")
	http.SetHeader("Expect","100-continue")
	http.SetHeader("Connection","Keep-Alive")
	http.SetHeader("Accept-Encoding","none")
	http.Client.Timeout=100000*time.Second
	res,err:=http.DoRequest("POST",url,data)
	if err!=nil{
		glog.Error("post请求报错",err)
		return nil
	}
	d:= res.ReadAll()
	return d
}